using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using GrpcServer_Demo;
using GrpcServer_Demo.Services;
using inter;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.IdentityModel.Tokens;

var builder = WebApplication.CreateBuilder(args);
builder.WebHost.ConfigureKestrel(x => { x.ListenAnyIP(5093, listenOptions => { listenOptions.Protocols = HttpProtocols.Http2; }); });
builder.Services.AddHttpContextAccessor();
builder.Services.AddGrpc(o => { o.Interceptors.Add<ParamInterceptor>(); });
builder.Services.AddAuthentication()
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters =
            new TokenValidationParameters
            {
                ValidateAudience = false,
                ValidateIssuer = false,
                ValidateActor = false,
                ValidateLifetime = true,
                IssuerSigningKey = GlobalConst.SecurityKey
            };
    });

builder.Services.AddGrpcClient<InternalService.InternalServiceClient>(o => { o.Address = new Uri("http://localhost:5093"); });
builder.Services.AddAuthorization(options =>
{
    options.AddPolicy(JwtBearerDefaults.AuthenticationScheme, policy =>
    {
        policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
        policy.RequireClaim(ClaimTypes.Name);
    });
    //添加一个策略
    // options.AddPolicy(GlobalConst.AdminPolicy, 
    //     p => { p.RequireClaim(GlobalConst.RoleClaim, "admin"); });
});


var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapGrpcService<UserService>();
app.MapGrpcService<InterServices>();
app.MapGet("/", () => "Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");
app.Run();


public static class GlobalConst
{
    public const string AdminPolicy = "admin";
    public const string RoleClaim = "role";
    public static readonly SymmetricSecurityKey SecurityKey = new SymmetricSecurityKey("Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a clientCommunication with gRPC endpoints must be made through a gRPC client. To learn how to create a clientCommunication with gRPC endpoints must be made through a gRPC client. To learn how to create a client"u8.ToArray());
}